<?php
declare (strict_types = 1);

namespace app\adminapi\controller;

use think\exception\ValidateException;
use think\Request;
use  think\facade\Filesystem;

class Image
{
    /**
     * 单文件上传方法
     * @return int
     */
    public function singleUpload(Request $request){
        try {
            $file = $request->file('file');
            validate(\app\adminapi\validate\Image::class)->check(['file' => $file]);
            $path = Filesystem::disk('public')->putFile( 'image', $file);
            return success(['data' => 'storage/'.$path]);
        }catch (ValidateException $exception) {
            return  fail(2001,$exception->getError());
        }

    }

    /**
     * 多文件上传
     * @param Request $request
     * @return \think\response\Json|void
     */
    public function multiUpload(Request $request){
        # 数组
        $files = $request->file('file');
        $success = [];# 上传成功的路径
        $error = []; # 上传失败的错误信息
        foreach ($files as $file) {
            # 里面捕获每个文件的错误信息
            try {
                validate(\app\adminapi\validate\Image::class)->check(['file' => $file]);
                $path = Filesystem::disk('public')->putFile( 'image', $file);
                $success[] = [
                    'path' => 'storage/'.$path
                ];
            }catch (ValidateException $exception) {
                $error[] = [
                    'name' => $file->getOriginalName(),
                    'msg' => $exception->getMessage(),
                ];
            }
        }
        return success(['success' => $success,'error' => $error]);
    }


}
